<template>
  <div class="home" style="height: 100%; width: 100%">
    <JwChat :taleList="list" @enter="bindEnter" @clickTalk="talkEvent" v-model="inputMsg"
            :toolConfig="tool" :quickList="quickList"
            :scrollType="'scroll'" :showRightBox='false' :height="'100%'" :width="'100%'">
      <template slot="tools">
        <div style="width:20rem;text-align:right;" @click="toolEvent('自定义')">
          <b slot="tools">
            <el-select v-model="completeType" class="m-2" placeholder="生成类型" size="small">
              <el-option
                  :key="0"
                  label="文本"
                  :value="0"
              />
              <el-option
                  :key="1"
                  label="图片"
                  :value="1"
              />
            </el-select>
            <el-button style="margin-left: 10px" @click="removeLocal" :size="'small'">清空聊天记录</el-button>
          </b>
        </div>
      </template>
    </JwChat>
  </div>
</template>

<script>
import axios from "axios";

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Chat",
  data() {
    return {
      eventSource: {},
      isLoading: false,
      imgTemplate: "<img data-src='{url}'/>",
      inputMsg: '',
      list: [],
      params: {},
      completeType: 0 , //0-文本 1-图片
      url: {
        imgDesc: '/api/common/openai/image/generations',
        streamReply: 'http://127.0.0.1:10086/stream/question',
      },
      openAiMsg: {
        date: "",
        text: {"text": ""},
        mine: false,
        name: "留恋人间不羡仙",
        img: "/image/one.jpeg"
      },
      tool: {
        callback: this.toolEvent
      },
      quickList: [
        {text: '这里是jwchat，您想了解什么问题。'},
        {text: 'jwchat是最好的聊天组件'},
        {text: '谁将烟焚散，散了纵横的牵绊；听弦断，断那三千痴缠。'},
        {text: '长夏逝去。山野间的初秋悄然涉足。'},
        {text: '江南风骨，天水成碧，天教心愿与身违。'},
        {text: '总在不经意的年生。回首彼岸。纵然发现光景绵长。'},
        {text: '外面的烟花奋力的燃着，屋里的人激情的说着情话'},
        {text: '假如你是云，我就是雨，一生相伴，风风雨雨；'},
        {text: '即使泪水在眼中打转，我依旧可以笑的很美，这是你学不来的坚强。'},
        {text: ' 因为不知来生来世会不会遇到你，所以今生今世我会加倍爱你。'},
      ]
    }
  },
  methods: {
    bindEnter(e) {
      // if(this.isLoading){
      //   this.$message.warning("请等待数据生成完成！")
      //   return
      // }
      // this.isLoading = true;
      const msg = this.inputMsg
      if (!msg) return;
      const msgObj = JSON.parse(JSON.stringify(this.openAiMsg))
      msgObj.date = this.$moment(new Date()).format('YYYY-MM-DD hh:mm:ss')
      msgObj.text.text = msg
      msgObj.name = '我'
      msgObj.mine = true
      //调用方法开始获取恢复
      this.list.push(msgObj)
      //判断消息希望返回的类型
      if (this.completeType==1) {
        this.replyImage(msg)
      } else {
        this.reply(msg)
      }
    },
    saveLocal(){
      this.$ls.set("list",JSON.stringify(this.list))
    },
    removeLocal(){
      this.$ls.set("list",JSON.stringify([]))
      this.list = [];
    },
    //流式回复消息，用户体验会更好
    reply(msg) {
      msg = '';
      this.isLoading = false; //eventsource 为长链接
      let that = this
      // 获取前后2000个字符（作为上下文）
      let i = 2000, j = this.list.length - 1;
      while (j >= 0) {
        let item = this.list[j];
        if (item.text.text == '请不要再👇我了') {
          j--;
          continue;
        }
        msg = item.text.text + "<br/>" + msg;
        //过长就跳过
        if(msg.length >= i){
          break;
        }
        j--;
      }
      //过长就截取
      if(msg.length > i){
        msg = msg.substring(msg.length - i, msg.length)
      }
      msg = encodeURIComponent(msg)
      // 使用流数据获取答案
      let reply = "";
      //初始化消息对象
      const openAiMsg = JSON.parse(JSON.stringify(this.openAiMsg))
      openAiMsg.date = this.$moment(new Date()).format('YYYY-MM-DD hh:mm:ss');
      openAiMsg.text.text = reply;


      //将消息体放入页面中
      this.list.push(openAiMsg)
      let index = this.list.length - 1;


      //开始请求接口获取回复
      let eventSourceUrl = this.url.streamReply + "?question=" + msg;
      this.eventSource = new EventSource(eventSourceUrl);

      //连接打开是回调
      this.eventSource.onopen = function () {
        if (that.eventSource.readyState == 1) {
          console.log('sse通道连接成功')
        }
      }
      // 服务器发送数据回调
      this.eventSource.addEventListener("load", function (e) {
        console.log("服务器发送给客户端的数据为:" + e.data);
      });
      //如果服务器响应报文中没有指明事件，默认触发message事件
      this.eventSource.addEventListener("message", function (e) {
        if (e.data == "[DONE]") {
          that.eventSource.close();
          that.saveLocal();
        }else{
          that.list[index].text.text = that.list[index].text.text + e.data
        }
        console.log("服务器发送给客户端的数据为:" + e.data);
      });
      //发生错误，则会触发error事件
      this.eventSource.addEventListener("error", function (e) {
        console.log("服务器发送给客户端的数据为:" + e.data);
        that.eventSource.close();
        that.saveLocal();
      });
    },
    //根据图片描述生成图片
    replyImage(desc) {
      let that = this;
      axios.get(this.url.imgDesc + "?description=" + desc).then(res => {
        let images = "";
        let imgArray = res.data.body;
        if(imgArray && imgArray.length > 0){
          for (let i = 0; i < imgArray.length; i++) {
            images += this.imgTemplate.replace('{url}', imgArray[i].url)
          }
        }else{
          images += "图片生成失败！可能涉及敏感词汇，请修改后重试！"
        }
        //初始化消息对象
        const openAiMsg = JSON.parse(JSON.stringify(this.openAiMsg))
        openAiMsg.date = this.$moment(new Date()).format('YYYY-MM-DD hh:mm:ss')
        openAiMsg.text.text = images
        that.list.push(openAiMsg)
      }).finally(()=>{
        this.isLoading = false;
        that.saveLocal();
      })
    },
    toolEvent(type, obj) {
      console.log('tools', type, obj)
    },
    //点击头像回调事件
    talkEvent(play) {
      if(play.type != 'img' || play.data.mine || this.isLoading){
        return;
      }
      //初始化消息对象
      const openAiMsg = JSON.parse(JSON.stringify(this.openAiMsg))
      openAiMsg.date = this.$moment(new Date()).format('YYYY-MM-DD hh:mm:ss');
      openAiMsg.text.text = '请不要再👇我了';
      this.list.push(openAiMsg)
    },
  },
  mounted() {
    let that = this;
    const img = 'https://www.baidu.com/img/flexible/logo/pc/result.png'
    let list = [
      // {
      //   "date": "2020/04/25 21:19:07",
      //   "text": {"text": "起床不"},
      //   "mine": false,
      //   "name": "留恋人间不羡仙",
      //   "img": "/image/one.jpeg"
      // },
      // {
      //   "date": "2020/04/25 21:19:07",
      //   "text": {"text": "<audio data-src='https://www.w3school.com.cn/i/horse.mp3'/>"},
      //   "mine": false,
      //   "name": "只盼流星不盼雨",
      //   "img": "/image/two.jpeg"
      // },
      // {
      //   "date": "2020/04/25 21:19:07",
      //   "text": {"text": "<img data-src='" + img + "'/>"},
      //   "mine": false,
      //   "name": "只盼流星不盼雨",
      //   "img": "/image/two.jpeg"
      // },
      // {
      //   "date": "2020/04/25 21:19:07",
      //   "text": {"text": "<img data-src='/image/three.jpeg'/>"},
      //   "mine": false,
      //   "name": "只盼流星不盼雨",
      //   "img": "/image/two.jpeg"
      // },
      // {
      //   "date": "2020/04/16 21:19:07",
      //   "text": {"text": "<video data-src='https://www.w3school.com.cn/i/movie.mp4' controls='controls' />"},
      //   "mine": true,
      //   "name": "JwChat",
      //   "img": "/image/three.jpeg"
      // },
      // {
      //   "date": "2021/03/02 13:14:21",
      //   "mine": false,
      //   "name": "留恋人间不羡仙",
      //   "img": "/image/one.jpeg",
      //   "text": {
      //     system: {
      //       title: '在接入人工前，智能助手将为您首次应答。',
      //       subtitle: '猜您想问:',
      //       content: [
      //         {
      //           id: `system1`,
      //           text: '组件如何使用'
      //         },
      //         {
      //           id: `system2`,
      //           text: '组件参数在哪里查看'
      //         },
      //         {
      //           id: 'system',
      //           text: '我可不可把组件用在商业'
      //         }
      //       ]
      //     }
      //   }
      // },
      // {
      //   "date": "2020/04/25 21:19:07",
      //   "text": {
      //     "text": "<i class='el-icon-document-checked' style='font-size:2rem;'/>",
      //     "subLink": {
      //       "text": "a.txt",
      //       "prop": {
      //         underline: false
      //       }
      //     },
      //   },
      //   "mine": false,
      //   "name": "留恋人间不羡仙",
      //   "img": "../image/one.jpeg"
      // },
      // {
      //   "date": "2020/04/25 21:19:07",
      //   "mine": false,
      //   "name": "留恋人间不羡仙",
      //   "img": "../image/one.jpeg",
      //   "text": {
      //     shop: {
      //       title: `2022年寒假读一本好书小学生三四五六年级课外读
      //         物阅读书籍经典儿童文学 回到远古和神仙们聊天 王云超著`,
      //       describe: '购买1-3件时享受单件价￥18.20，超出数量以结算价为准，仅限购买一次:',
      //       price: '999.99',
      //       cover: '../image/two.jpeg',
      //       tags: [
      //         {name: '第二件半价'},
      //         {name: '送50元优惠'},
      //         {name: '满1件,送50元优惠'},
      //       ]
      //     }
      //   }
      // }
    ]
    let arr = this.$ls.get("list");
    if(arr){
      list = JSON.parse(arr);
    }
    this.list = list
  }
}
</script>

<style lang="less">
.chatPage[data-v-035fd875] .taleBox {
    height: 80%!important;
}
</style>